package com.vots.web.controller.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;
import org.springframework.context.i18n.LocaleContextHolder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.vots.common.annotation.Anonymous;
import com.vots.common.config.RuoYiConfig;
import com.vots.common.core.controller.BaseController;
import com.vots.common.core.domain.AjaxResult;
import com.vots.common.core.domain.model.LoginUser;
import com.vots.common.utils.SecurityUtils;
import com.vots.common.utils.StringUtils;
import com.vots.common.utils.file.FileUploadUtils;
import com.vots.common.utils.file.FileUtils;
import com.vots.framework.config.ServerConfig;
import com.vots.framework.web.service.TokenService;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

/**
 * 通用 请求处理
 * 
 * @author ruoyi
 */
@Controller
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    
    @Autowired
    private TokenService tokenService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/common/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + FileUtils.stripPrefix(resource);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 切换语言
     */
    @Anonymous
    @PostMapping("/common/language")
    @ResponseBody
    public AjaxResult changeLanguage(@RequestBody Map<String, String> params, HttpServletRequest request)
    {
        try
        {
            String language = params.get("language");
            log.info("Received language change request: {}", language);
            log.info("All params: {}", params);
            
            if (StringUtils.isEmpty(language)) {
                log.warn("Language parameter is empty");
                return AjaxResult.error("Language parameter is required");
            }
            
            // 设置Spring标准的session key，保证LocaleResolver能识别
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale(language));
            log.info("Spring SessionLocaleResolver set to: {}", language);
            
            // 兼容旧逻辑，保留lang字段（可选）
            request.getSession().setAttribute("lang", language);
            log.info("Language set in session: {}", language);
            
            // 设置LocaleContextHolder，使菜单服务能够获取到正确的语言（当前请求线程）
            Locale locale = new Locale(language);
            LocaleContextHolder.setLocale(locale);
            log.info("LocaleContextHolder set to: {}", locale);
            
            Map<String, Object> result = new HashMap<>();
            result.put("language", language);
            result.put("message", "Language changed successfully");
            result.put("sessionId", request.getSession().getId());
            
            log.info("Language change successful, returning: {}", result);
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("Failed to change language: " + e.getMessage());
        }
    }

    /**
     * 获取当前语言
     */
    @Anonymous
    @GetMapping("/common/language")
    @ResponseBody
    public AjaxResult getCurrentLanguage(HttpServletRequest request)
    {
        try
        {
            String language = (String) request.getSession().getAttribute("lang");
            if (StringUtils.isEmpty(language))
            {
                language = "en"; // 默认英文，与前端保持一致
            }
            
            // 添加调试日志
            log.info("Current language from session: {}", language);
            
            Map<String, Object> result = new HashMap<>();
            result.put("language", language);
            result.put("sessionId", request.getSession().getId());
            
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            log.error("Failed to get current language", e);
            return AjaxResult.error("Failed to get current language: " + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/common/user")
    @ResponseBody
    public AjaxResult getUserInfo()
    {
        try
        {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (StringUtils.isNotNull(loginUser))
            {
                Map<String, Object> result = new HashMap<>();
                result.put("user", loginUser.getUser());
                result.put("roles", loginUser.getUser().getRoles());
                result.put("permissions", loginUser.getPermissions());
                return AjaxResult.success(result);
            }
            return AjaxResult.error("User not logged in");
        }
        catch (Exception e)
        {
            return AjaxResult.error("Failed to get user info: " + e.getMessage());
        }
    }
}
